<template>
  <el-dialog
    :title="!form.menuId ? '添加菜单' : '修改菜单'"
    :close-on-click-modal="false"
    v-model="isShow"
    width="600px"
    @close="close"
  >
    <el-form ref="rulesForm" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="上级菜单">
        <el-cascader
          v-model="form.selectParent"
          :options="menuOptions"
          :props="{
            value: 'menuId',
            label: 'menuName',
            expandTrigger: 'hover',
            children: 'children',
            checkStrictly: true,
          }"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="form.menuType">
          <el-radio label="M">目录</el-radio>
          <el-radio label="C">菜单</el-radio>
          <el-radio label="F">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
        <el-popover
          placement="bottom-start"
          width="460"
          trigger="click"
          @show="$refs['iconSelect'].reset()"
        >
          <icon-select ref="iconSelect" @selected="selected" />
          <template #reference>
            <el-input v-model="form.icon" placeholder="点击选择图标" readonly>
              <template #prefix>
                <svg-icon
                  v-if="form.icon"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else class="el-icon-search el-input__icon"></i>
              </template>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <div class="search-form2">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item v-if="form.menuType != 'F'" label="是否外链">
          <el-radio-group v-model="form.isFrame">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.menuType != 'F'" label="路由地址" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item v-if="form.menuType != 'F'" label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item v-if="form.menuType == 'C'" label="组件名称" prop="componentName">
          <el-input v-model="form.componentName" placeholder="请输入组件名称" />
        </el-form-item>
        <el-form-item v-if="form.menuType != 'M'" label="权限标识">
          <el-input v-model="form.perms" placeholder="请权限标识" maxlength="50" />
        </el-form-item>
        <el-form-item v-if="form.menuType != 'F'" label="显示状态">
          <el-radio-group v-model="form.visible">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.menuType != 'F'" label="菜单状态">
          <el-radio-group v-model="form.enable">
            <el-radio :label="true">正常</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.menuType == 'C'" label="是否缓存">
          <el-radio-group v-model="form.isCache">
            <el-radio :label="true">缓存</el-radio>
            <el-radio :label="false">不缓存</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { handleTree, getFathersById, getTreeData } from '@/utils'
import { useStore } from 'vuex'
import { reactive, watch, computed, toRefs, ref, defineComponent } from 'vue'
import { ElMessage } from 'element-plus'
import dialog from '@/mixins/dialog'
import IconSelect from '@/components/IconSelect/index.vue'
import { Menu, StateType as MenuStateType } from '@/store/modules/system/menu'

interface FormType extends Menu {
  selectParent: Array<number>;
}
interface DataType {
  menuOptions: Array<Menu>;
  form: FormType;
  rules: object;
}
export default defineComponent({
  name: 'AUMenu',
  emits: ['onRefresh', 'close'], // this line
  components: { IconSelect },
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const { dialogM } = dialog(props, context)
    const store = useStore<{menu: MenuStateType}>()
    const data = reactive<DataType>({
      menuOptions: [],
      form: {
        menuId: null,
        menuName: '',
        parentId: null,
        roleSort: 1,
        orderNum: 1,
        path: null,
        componentName: null,
        component: null,
        isCache: true,
        visible: true,
        perms: null,
        icon: null,
        remark: null,
        isFrame: false,
        enable: true,
        menuType: 'M',
        selectParent: []
      },
      rules: {
        menuName: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '路由地址不能为空', trigger: 'blur' }
        ]
      }
    })
    const rulesForm = ref<HTMLElement>()
    const menuData = computed(() => {
      return store.state.menu.data
    })
    const selectParent = computed(() => {
      return data.form.selectParent
    })
    const getTreeSelect = async() => {
      const res = await store.dispatch('menu/getMenuList')
      const list = handleTree(res.data, 'menuId')
      data.menuOptions = getTreeData(list) as Array<Menu>
    }
    watch(selectParent, (val) => {
      if (val && val.length) {
        data.form.parentId = val[val.length - 1]
      } else {
        data.form.parentId = null
      }
    })
    watch(() => props.value, async(val) => {
      if (val) {
        await getTreeSelect()
        if (menuData.value) {
          store.dispatch('menu/getMenu', menuData.value.menuId).then(res => {
            data.form = res.data
            data.form.selectParent = getFathersById(data.form.parentId, data.menuOptions, 'menuId')
          })
        }
      } else {
        data.form = {
          menuId: null,
          menuName: '',
          parentId: null,
          roleSort: 1,
          orderNum: 1,
          path: null,
          componentName: null,
          component: null,
          isCache: true,
          visible: true,
          perms: null,
          icon: null,
          remark: null,
          isFrame: false,
          enable: true,
          menuType: 'M',
          selectParent: []
        }
        rulesForm.value && (rulesForm.value as any).resetFields()
      }
    })
    const submit = () => {
      (rulesForm.value as any).validate((valid: boolean) => {
        if (valid) {
          if (menuData.value) {
            store.dispatch('menu/updateMenu', data.form).then(() => {
              ElMessage({
                message: '修改成功',
                type: 'success'
              })
              context.emit('onRefresh')
              dialogM.close()
            })
          } else {
            store.dispatch('menu/addMenu', data.form).then(() => {
              ElMessage({
                message: '新增成功',
                type: 'success'
              })
              context.emit('onRefresh')
              dialogM.close()
            })
          }
        }
      })
    }
    const selected = (name: string) => {
      data.form.icon = name
    }
    return {
      ...toRefs(dialogM),
      ...toRefs(data),
      rulesForm,
      submit,
      selected
    }
  }
})
</script>
